import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 38917
 * Date: 2025-04-01
 * Time: 20:01
 */
public class Reflect {
    public static void reflectPublicConstructor() throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        Class<?> c = Class.forName("Student");
        //实例化对象
        Student student = (Student) c.newInstance();
        Field nameField = c.getField("name");
        Field ageField = c.getField("age");
        nameField.set(student,"逆天而行");
        ageField.set(student,18);
        System.out.println(student);
        System.out.println(nameField + "=====" + ageField);
    }

    public static void reflectPrivateConstructor() throws ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchMethodException {
        Class<?> c = Class.forName("Student");
        //获取私有构造方法
        Constructor<?> declaredConstructor = c.getDeclaredConstructor(String.class,int.class);
        declaredConstructor.setAccessible(true);
        //实例化对象
        Student student = (Student) declaredConstructor.newInstance("逆天而行",18);
        System.out.println(student);
        //获取私有成员方法
        Method method = c.getDeclaredMethod("function", int.class);
        method.setAccessible(true);
        method.invoke(student,18);
    }
    //
    public static void main(String[] args) throws ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchMethodException, NoSuchFieldException {
        reflectPublicConstructor();
        System.out.println("==========================");
        reflectPrivateConstructor();
    }
}
